package au.com.handsunited.web.controller.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import au.com.handsunited.model.invitations.Invitation;
import au.com.handsunited.service.UserService;
import au.com.handsunited.service.impl.UserServiceImpl;
import au.com.handsunited.web.command.user.UserInviteCommand;
import au.com.handsunited.web.controller.entity.AbstractInviteController;
import au.com.handsunited.web.session.SessionSupport;

/**
 *
 * @author arunda
 */
public class InviteUserController extends AbstractInviteController {

	private UserService userService;

	private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	/**
	 *
	 */
	public InviteUserController() {
		setCommandClass(UserInviteCommand.class);
	}


	/**
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {

		UserInviteCommand userInviteCommand = (UserInviteCommand) command;

		String emailAddresses 	= userInviteCommand.getEmailAddresses();
		String message 			= userInviteCommand.getMessage();

		Map<String, List<Invitation>> invitationsMap =
			userService.inviteUsers(SessionSupport.getUser(request), emailAddresses, message);

		List<String> validEmailAddresses = getEmailAddressesFromInvitations(invitationsMap.get(Invitation.VALID_EMAILADDRESSES));
		List<String> invalidEmailAddresses = getEmailAddressesFromInvitations(invitationsMap.get(Invitation.VALID_EMAILADDRESSES));

		Map<String, String> model = new HashMap<String, String>();
		model.put(Invitation.VALID_EMAILADDRESSES, StringUtils.join(validEmailAddresses, ", "));
		model.put(Invitation.INVALID_EMAILADDRESSES, StringUtils.join(invalidEmailAddresses, ", "));

		ModelAndView mav = new ModelAndView(getSuccessView(), model);

		return mav;
	}


	/**
	 * @param userService the userService to set
	 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
